# coding = utf-8
import os
import time

from member.models import Retailer, RetailerImage, Employee, BonusPoint, PointConsumption, WxPermission, WxRole
from wine import settings
from django.db.models import Q, Sum

from rest_framework import status, filters
from rest_framework.decorators import action
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from users.api.utils import get_user_by_request

from .serializers import RetailerSerializer, RetailerImageSerializer, EmployeeSerializer, BonusPointSerializer, \
    PointConsumptionSerializer, RetailerListSerializer, WxPermissionSerializer, WxRoleSerializer


class RetailerListAPIView(ListAPIView):
    """商家列表"""
    authentication_classes = ()
    permission_classes = ()
    serializer_class = RetailerListSerializer
    queryset = Retailer.objects.filter(flag=1)
    pagination_class = None


class RetailerViewSet(ModelViewSet):
    """商家"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Retailer.objects.all()
    serializer_class = RetailerSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class RetailerImageViewSet(ModelViewSet):
    """商家图片"""
    # authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = RetailerImage.objects.all()
    serializer_class = RetailerImageSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        user = get_user_by_request(self.request)

        if user is None:
            return queryset.none()

        retailer_id = self.request.query_params.get("retailer_id")

        if retailer_id:
            queryset = queryset.filter(retailer_id=retailer_id)

        return queryset


class RetailerImageUploadAPIView(APIView):
    # authentication_classes = ()

    def post(self, request, *args, **kwargs):
        # 接收文件
        file = request.FILES.get('image', None)
        retailer_id = request.data.get("retailer_id", None)

        print(file, retailer_id)
        if file and retailer_id:
            upload_path = RetailerImage.image.field.upload_to
            dirs = os.path.join(settings.MEDIA_ROOT, upload_path)
            if not os.path.exists(dirs):
                os.makedirs(dirs)

            file_info = file.name.rsplit(".", 1)
            old_file_name = file_info[0]
            file_suffix = file_info[1]
            file_name = '{0}_{1}.{2}'.format(old_file_name, int(time.time()), file_suffix)
            file_path = os.path.join(dirs, file_name)

            with open(file_path, 'wb') as f:
                for chunk in file.chunks():
                    f.write(chunk)

            file_url = '{0}{1}'.format(upload_path, file_name)
            data = {
                'retailer_id': retailer_id,
                'name': file.name,
                'image': file_url,
            }

            obj = RetailerImage.objects.create(**data)
            dict_obj = {
                "id":   obj.id,
                "name": obj.name,
                "retailer_id": obj.retailer_id,
                "image": "{}://{}{}".format(request.scheme, request.get_host(), obj.image.url),
            }

            msg = {
                "status_code": status.HTTP_200_OK,
                "file": dict_obj,
            }
            return Response(msg)

        return Response({"status_code": status.HTTP_401_UNAUTHORIZED, "message": "上传失败!"})


class EmployeeViewSet(ModelViewSet):
    """商家授权员工"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = Employee.objects.all()
    serializer_class = EmployeeSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        retailer_id = self.request.query_params.get("retailer_id", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=retailer_id)

        if name:
            queryset = queryset.filter(name__contains=name)

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class BonusPointViewSet(ModelViewSet):
    """商家积分赠送明细"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = BonusPoint.objects.all()
    serializer_class = BonusPointSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        order_no = self.request.query_params.get("order_no", None)
        retailer_id = self.request.query_params.get("retailer", None)
        wx_retailer_id = self.request.query_params.get("retailer_id", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if wx_retailer_id and int(wx_retailer_id) > 0:
            queryset = queryset.filter(retailer_id=int(wx_retailer_id))

        if order_no:
            queryset = queryset.filter(order_no__contains=order_no)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(customer_name__contains=name) | Q(openid__contains=name) | Q(customer_openid__contains=name))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class PointConsumptionViewSet(ModelViewSet):
    """客户积分消费"""
    # authentication_classes = ()
    permission_classes = ()
    queryset = PointConsumption.objects.all()
    serializer_class = PointConsumptionSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        name = self.request.query_params.get("name", None)
        employee_name = self.request.query_params.get("employee_name", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name))

        if employee_name:
            queryset = queryset.filter(Q(employee_name__contains=employee_name) | Q(employee_openid__contains=employee_name))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class BonusStatsAPIView(APIView):
    """商家积分统计"""
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        retailer_id = request.query_params.get("retailer_id", None)
        name = request.query_params.get("name", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        queryset = BonusPoint.objects.all()

        if retailer_id and int(retailer_id) > 0:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(customer_name__contains=name))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        queryset = queryset.filter(order_key__isnull=False)

        results = queryset.aggregate(scores=Sum('score'), unused_scores=Sum('unused_score'))

        return Response(results)


class ConsumeStatsAPIView(APIView):
    """商家积分统计"""
    permission_classes = ()

    def get(self, request, *args, **kwargs):
        name = request.query_params.get("name", None)
        search_date = self.request.query_params.getlist("search_date[]", None)

        queryset = PointConsumption.objects.all()

        if name:
            queryset = queryset.filter(Q(name__contains=name) | Q(openid__contains=name))

        if search_date and len(search_date) == 2:
            queryset = queryset.filter(update_time__date__range=(search_date[0], search_date[1]))

        results = queryset.aggregate(scores=Sum('score'))

        return Response(results)


class RetailerPermsListAPIView(ListAPIView):
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = WxPermission.objects.all()
    serializer_class = WxPermissionSerializer


class RetailerPermissionViewSet(ModelViewSet):
    permission_classes = ()
    queryset = WxPermission.objects.all()
    serializer_class = WxPermissionSerializer

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class RetailerRoleViewSet(ModelViewSet):
    permission_classes = ()
    queryset = WxRole.objects.all()
    serializer_class = WxRoleSerializer

    def get_queryset(self):
        queryset = super().get_queryset()

        retailer_id = self.request.query_params.get("retailer_id", None)

        if retailer_id:
            queryset = queryset.filter(retailer_id=int(retailer_id))

        return queryset

    @action(methods=['delete'], detail=False)
    def batch_delete(self, request, *args, **kwargs):
        select_ids = request.data.get("select_ids", None)
        if not select_ids:
            msg = {"status_code": status.HTTP_404_NOT_FOUND, "message": "删除失败!"}
            return Response(data=msg, status=status.HTTP_404_NOT_FOUND)

        self.serializer_class.Meta.model.objects.filter(id__in=select_ids).delete()
        msg = {"status_code": status.HTTP_204_NO_CONTENT, "message": "删除成功!"}
        return Response(data=msg, status=status.HTTP_204_NO_CONTENT)


class RetailerRoleListAPIView(ListAPIView):
    authentication_classes = ()
    permission_classes = ()
    pagination_class = None
    queryset = WxRole.objects.all()
    serializer_class = WxRoleSerializer
